import axios from "axios";
import Vue from 'vue';
import store from "../store";

var url = "http://221.224.198.226:18080";

// 创建axios实例
const service = axios.create({
  baseURL: url, // api的base_url
  timeout: 30000, // 请求超时时间 30000
  headers: {
    // 'Content-Type':'application/x-www-form-urlencoded'
    'Content-Type': 'application/json'
  }

});

// request拦截器
service.interceptors.request.use(
  config => {
    console.log(config, "请求参数");
    var token = localStorage.getItem('judo_token') || "";
    if (token.length == 0) {
      Promise.reject(error);
    }
    config.headers.Authorization = 'JWT ' + localStorage.token
    return config;

  },
  error => {
    Promise.reject(error);
  }
);

// respone拦截器
service.interceptors.response.use(
  response => {
    console.log(response, "===response====");
    const Result = response.data;
    console.log("code:" + Result.ResultCode);

    var errMsg = "";

    switch (Result.ResultCode) {
      case 1000:
        console.log("resolve");
        return Promise.resolve(response.data);
        break;
      case 1001:
        errMsg = "Token失效,请登陆";
        break;
      default:
        errMsg = Result.ResultMsg;
        break;
    }
    if (errMsg.length > 0) {
      alert(errMsg);
    }
    return Promise.reject(Result);
  },
  error => {
    let ErrorMsg = error.message;
    if (error.code == "ECONNABORTED") ErrorMsg = "请求超时，请稍后再试。";
    return Promise.reject(error);
  }
);

export default service;
